<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom:10px">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>管理角色</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" style="margin-bottom:10px" @click="AddRoleDialogVisible = true">
            添加角色
          </el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" border stripe>
        <el-table-column type="index" label="#" />
        <el-table-column label="角色名称" prop="roleName" />
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.roleId)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.roleId)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row.roleId)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        v-if="isShowTree"
        ref="treeRef"
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="permissionId"
        :default-checked-keys="defKeys"
        :default-expanded-keys="defKeys"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogClosed">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="AddRoleDialogVisible"
      width="40%"
      @close="addRoleDialogClosed"
    >
      <el-form
        ref="addRoleFormRef"
        :model="addRoleForm"
        :rules="addRoleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleDialogVisible"
      width="40%"
      @close="editRoleDialogClosed"
    >
      <el-form
        ref="editRoleFormRef"
        :model="editRoleForm"
        :rules="editRoleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="删除角色"
      :visible.sync="deleteRoleDialogVisible"
      width="40%"
      @close="deleteRoleDialogClosed"
    >
      <el-form
        label-width="100px"
      >
        确认删除此角色？
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'Role',
  data() {
    return {
      // 所有角色列表
      rolesList: [
      ],
      // 分配权限框
      setRightDialogVisible: false,
      // 权限列表
      rightsList: [],
      //  树形控件的属性绑定对象
      treeProps: {
        label: 'permissionName',
        children: 'sonPermissions'
      },
      //   默认选中节点ID值
      defKeys: [],
      //   添加用户对话框
      AddRoleDialogVisible: false,
      // 添加角色表单
      addRoleForm: {},
      //   添加角色表单验证
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      //   编辑角色信息
      editRoleForm: {},
      editRoleDialogVisible: false,
      editRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 删除用户
      deleteRoleDialogVisible: false,
      roleId: '',
      allList: [],
      isShowTree: false
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    getRolesList() {
      axios.get('/role/getRoles')
        .then((res) => {
          this.rolesList = res.data.data
        })
        .catch((err) => {
          this.$message.info(err.msg)
        })
    },

    // 获取权限树
    getrightsList() {
      axios.get('/rolePer/allPermission')
        .then(res => {
          this.rightsList = res.data.data
        })
        .catch(err => {
          console.error(err)
        })
    },

    // 分配权限框
    showSetRightDialog(role) {
      // 获取角色的所有权限
      this.roleId = role

      axios.get(`/rolePer/rolePermission/${role}`)
        .then(res => {
          for (var i = 0; i < res.data.LeafList.length; i++) {
            this.defKeys.push(res.data.LeafList[i].permissionId)
          }
          for (var j = 0; j < res.data.AllList.length; j++) {
            this.allList.push(res.data.AllList[j].permissionId)
          }
          this.getrightsList()
        })
        .catch(err => {
          console.error(err)
        })
      //   获取权限树

      this.setRightDialogVisible = true
      this.isShowTree = true
    },

    // 分配权限
    allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 增加权限
      const add = keys.filter(v => !this.allList.includes(v))
      var addlist = []
      for (var i = 0; i < add.length; i++) {
        addlist[i] = { permissionId: add[i], roleId: this.roleId }
      }
      if (addlist.length > 0) {
        axios.post('/rolePer/insertPermission', {
          list: addlist
        })
          .then(() => {

          })
          .catch((err) => {
            this.$message.info(err.msg)
          })
      }
      // 删除权限
      const del = this.allList.filter(v => !keys.includes(v))
      var dellist = []
      for (var j = 0; j < del.length; j++) {
        dellist[j] = { permissionId: del[j], roleId: this.roleId }
      }
      if (dellist.length > 0) {
        axios.post('/rolePer/deletePermission', {
          list: dellist
        })
          .then(() => {
            this.$message.success('成功分配权限')
            this.visTree = false
            this.setRightDialogVisible = false
            this.isShowTree = false
          })
          .catch((err) => {
            this.$message.info(err.msg)
          })
      } else {
        this.$message.info('成功分配权限')
        this.visTree = false
        this.setRightDialogVisible = false
        this.isShowTree = false
      }
    },

    // 关闭分配权限
    setRightDialogClosed() {
      this.defKeys = []
      this.allList = []
      this.setRightDialogVisible = false
      this.isShowTree = false
    },

    // 添加角色对话框的关闭
    addRoleDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },

    // 添加角色
    addRoles() {
      axios.post('/role/insert', {
        roleName: this.addRoleForm.roleName
      })
        .then(() => {
          this.$message.success('添加成功')
          this.AddRoleDialogVisible = false
          this.getRolesList()
        })
        .catch(err => {
          console.error(err)
        })
    },

    // 编辑角色
    showEditDialog(role) {
      this.editRoleDialogVisible = true
      this.roleId = role
    },

    editRoles() {
      axios.post('/role/update', {
        roleId: this.roleId,
        roleName: this.editRoleForm.roleName
      })
        .then(() => {
          this.$message.success('编辑角色成功')
          this.editRoleDialogVisible = false
          this.getRolesList()
        })
        .catch(err => {
          console.error(err)
        })
    },
    editRoleDialogClosed() {
      this.editRoleDialogVisible = false
    },

    // 删除角色
    removeRoleById(role) {
      this.deleteRoleDialogVisible = true
      this.roleId = role
    },
    deleteRoles() {
      this.axios.get(`/role/delete/${this.roleId}`)
        .then(() => {
          this.$message.info('删除成功')
          this.deleteRoleDialogVisible = false
          this.getRolesList()
        })
        .catch(err => {
          console.error(err)
        })
    },
    deleteRoleDialogClosed() {
      this.deleteRoleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
